<script setup lang="ts">
import { ref, watch } from 'vue';

import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';

import { Card, DatePicker, Form, Input, message, Select } from 'ant-design-vue';

import {
  createBusinessEmployee,
  getCurrentEmployeeProfile,
} from '#/api/per/businessEmployee';

const props = defineProps<{ data?: any }>();

// 表单引用
const formRef = ref();

// 表单数据
const form = ref<any>({});

// 同步 props 到 form
watch(
  () => props.data, // 监听props.data的变化
  async (val) => {
    // 使用异步函数

    try {
      const data = await getCurrentEmployeeProfile(
        { employeeId: props.data.employeeId },
        false,
      ); // 获取员工数据
      Object.assign(form.value, data || {}); // 填充表单数据
    } catch (error) {
      console.error('获取员工数据失败', error);
    }
  },
  { immediate: true }, // 初始时立即执行一次
);

//  表单验证规则
const rules = {
  fullName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  teacherCertificate: [
    { required: true, message: '请输入教师资格证号', trigger: 'blur' },
  ],
  cardType: [{ required: true, message: '请选择证件类型', trigger: 'change' }],
  idcard: [
    { required: true, message: '请输入证件号码', trigger: 'blur' },
    {
      pattern: /^[A-Z0-9]+$/i,
      message: '证件号码只能包含字母或数字',
      trigger: 'blur',
    },
  ],
  mobile: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号',
      trigger: 'blur',
    },
  ],
  photoUrl: [{ required: true, message: '请上传头像', trigger: 'change' }],
};

// 子组件：handleSave
const handleSave = async (): Promise<boolean> => {
  try {
    // 1. 校验表单
    const valid = await formRef.value?.validate();
    if (!valid) return false; // 校验未通过

    // 2. 保存数据
    await createBusinessEmployee(form.value);

    return true;
  } catch (error) {
    message.error('保存失败', error);
    return false; // 保存失败
  }
};

async function getFormData() {
  await formRef.value?.validate();
  return form.value;
}

// 暴露给父组件
defineExpose({ handleSave, getFormData });
</script>

<template>
  <div class="space-y-4">
    <!-- 基本信息 -->
    <Form ref="formRef" layout="horizontal" :model="form" :rules="rules">
      <Card title="基本信息" :bordered="false" class="mb-4">
        <div class="space-y-4">
          <!-- 头像单独一行 -->
          <Form.Item label="头像" name="photoUrl">
            <ImageUpload
              v-model:value="form.photoUrl"
              :max-number="1"
              :params="{
                fileCategoriesCode: 'GRZH',
                objectId: 'GRTX',
                objectType: '个人头像',
              }"
            />
          </Form.Item>

          <!-- 两列表单布局 -->
          <div class="grid grid-cols-2 gap-4">
            <!-- 姓名 -->
            <Form.Item label="姓名" name="fullName">
              <Input v-model:value="form.fullName" placeholder="请输入姓名" />
            </Form.Item>

            <!-- 证件类型 -->
            <Form.Item label="证件类型" name="cardType">
              <Select
                v-model:value="form.cardType"
                allow-clear
                :options="getDictOptions(DICT_TYPE.SYSTEM_CARD_TYPE, 'string')"
                placeholder="请选择证件类型"
              />
            </Form.Item>

            <!-- 证件号码 -->
            <Form.Item label="证件号码" name="idcard">
              <Input v-model:value="form.idcard" placeholder="请输入证件号码" />
            </Form.Item>

            <Form.Item label="曾用名">
              <Input v-model:value="form.formerName" />
            </Form.Item>

            <Form.Item label="民族">
              <Select
                v-model:value="form.ethnicity"
                allow-clear
                :options="getDictOptions(DICT_TYPE.SYSTEM_NATION, 'string')"
                placeholder="请选择民族"
              />
            </Form.Item>

            <Form.Item label="籍贯">
              <Input v-model:value="form.nativePlace" />
            </Form.Item>

            <Form.Item label="出生地">
              <Input v-model:value="form.birthPlace" />
            </Form.Item>

            <Form.Item label="政治面貌">
              <Select
                v-model:value="form.politicalStatus"
                allow-clear
                :options="
                  getDictOptions(DICT_TYPE.SYSTEM_POLITICALINFO, 'string')
                "
                placeholder="请选择政治面貌"
              />
            </Form.Item>

            <Form.Item label="入党时间" name="partyJoinDate">
              <DatePicker
                v-model:value="form.partyJoinDate"
                style="width: 100%"
                :show-time="false"
                format="YYYY-MM-DD"
                value-format="x"
              />
            </Form.Item>

            <Form.Item label="编制类型">
              <Select
                v-model:value="form.staffType"
                allow-clear
                :options="getDictOptions(DICT_TYPE.PER_STAFF_TYPE, 'string')"
                placeholder="请选择编制类型"
              />
            </Form.Item>

            <Form.Item label="教师资格证号" name="teacherCertificate">
              <Input
                v-model:value="form.teacherCertificate"
                placeholder="请输入教师资格证号"
              />
            </Form.Item>
          </div>
        </div>
      </Card>

      <!-- 联系与地址 -->
      <Card title="联系与地址" :bordered="false" class="mb-4">
        <div class="grid grid-cols-2 gap-4">
          <Form.Item label="联系电话" name="mobile">
            <Input v-model:value="form.mobile" placeholder="请输入联系电话" />
          </Form.Item>
          <Form.Item label="常住地址">
            <Input v-model:value="form.currentAddress" />
          </Form.Item>
          <Form.Item label="户籍地址">
            <Input v-model:value="form.householdAddress" />
          </Form.Item>
          <Form.Item label="家庭地址">
            <Input v-model:value="form.homeAddress" />
          </Form.Item>
        </div>
      </Card>
    </Form>
  </div>
</template>

<style scoped>
.shadow-sm {
  box-shadow: 0 1px 3px rgb(0 0 0 / 8%);
}

.space-y-4 > * + * {
  margin-top: 1rem;
}
</style>
